package data;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.*;
import java.io.File;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@XmlRootElement(name = "urlset")
@XmlAccessorType(XmlAccessType.FIELD)
public class Sitemap {
    @XmlAttribute
    public String xmlns;

    @XmlElement(name = "url")
    public List<Url> urls = new ArrayList<Url>();

    public Sitemap() {
        xmlns="http://www.sitemaps.org/schemas/sitemap/0.9";
    }

    public static void main(String[] args) throws JAXBException {
//        Sitemap sitemap = new Sitemap();
//
//        sitemap.urls.add(new Url("http://extramobi.ru/pricelist/", "2011-10-22"));
//        sitemap.urls.add(new Url("http://extramobi.ru/auxpage_contacts", "2011-10-22"));
//
//        sitemap.xmlns="http://www.sitemaps.org/schemas/sitemap/0.9";

        JAXBContext jaxbContext = JAXBContext.newInstance(Sitemap.class);
        Sitemap sitemap = (Sitemap) jaxbContext.createUnmarshaller().unmarshal(new File("data/extramobi/sitemap-template.xml"));

        sitemap.urls.add(new Url("http://extramobi.ru/pricelist/"));
        sitemap.urls.add(new Url("http://extramobi.ru/auxpage_contacts"));
        sitemap.xmlns="http://www.sitemaps.org/schemas/sitemap/0.9";

        StringWriter writer = new StringWriter();
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(sitemap, writer);
        System.out.println(writer);
    }

    @XmlRootElement
    public static class Url {
        static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        @XmlElement
        public String loc;

        public void setLastmod() {
            this.lastmod = dateFormat.format(new Date());
        }

        @XmlElement
        public String lastmod;

        public Url() {
            this.lastmod = dateFormat.format(new Date());
        }


        @XmlElement
        public String changefreq = "weekly";

        @XmlElement
        public String priority = "0.8";

        public Url(String url) {
            this();
            this.loc = url;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            Url url = (Url) o;

            if (loc != null ? !loc.equals(url.loc) : url.loc != null) return false;

            return true;
        }

        @Override
        public int hashCode() {
            return loc != null ? loc.hashCode() : 0;
        }
    }
}
